<template>
  <div class="workInstructionLibrary flowCloumn h100">
    <div class="constentmain h100">
      <list-table-new v-bind="tableSetting" ref="klTable"></list-table-new>
    </div>
    <dialogPublic
      :title="title"
      :show.sync="show"
      v-if="show"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <editForm
        :formConfig="formConfig"
        ref="editForm"
        :formData="editFormData"
      ></editForm>
      <div class="upload-file">
        <label>上传附件</label>
        <attachFormNew
          style="width: 60%"
          :attachSetting="attachSetting"
          @uploadSuccess="uploadSuccess"
          ref="attachForm"
          :limit="1"
          :isDelete="isDelete"
          :disabled="disabled"
        ></attachFormNew>
      </div>
    </dialogPublic>
  </div>
</template>
<script>
import {
  queryInstructionList,
  addInstruction,
  updateInstruction,
  deleteInstruction,
  setCommonInstruction,
} from "@/api/standardManagement/workInstructionLibrary.js";
import { deleteFilesByIds, getAttachList } from "@/api/common";
export default {
  props: {
    pageType: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      title: "",
      uploadTitle: "只能上传doc/pdf文件",
      show: false,
      isDelete: false,
      disabled: false,
      tableSetting: {
        pageConfig: {
          pageCode: "workInstructionLibrary",
          userId: this.$store.getters.userInfo.namePy,
        },
        selectionShow: true,
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },

          queryData: {
            page: 1,
            pageSize: 15,
            publicStatus: 1,
          },
          searchArr: [
            {
              type: "input",
              label: "文件名",
              model: "name",
              placeholder: "请输入文件名",
            },
            {
              type: "deviceClassify",
              label: "设备分类",
              model: "typeName",
              idsStr: "typeId",
            },
            {
              type: "select",
              label: "作业类型",
              model: "group",
              option: this.$store.getters.dirtData("standard_instruction_type"),
            },
            {
              type: "select",
              label: "适用范围",
              model: "appids",
              multiple: true,
              option: this.$store.getters.appAuthList,
            },
          ],
        },
        //过滤器的值
        filterFormData: {},
        //过滤器的默认值
        defaultFilterData: {},
        userCustomData: [],
        actionList: [
          {
            name: "上传",
            icon: "el-icon-plus",
            disabled: !this.$store.getters.isBtnAuth("upload"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.toUpload();
            },
          },
          {
            name: "设为公共标准",
            disabled: !this.$store.getters.isBtnAuth("setPublic"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.toPublicStandard();
            },
          },
          {
            name: "删除",
            icon: "el-icon-delete",
            disabled: !this.$store.getters.isBtnAuth("delete"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.isDelete = false;
              this.delete();
            },
          },
        ],
        tableMethods: {
          //点击行的方法
          rowClick: (row) => {
            // this.editFormData = row;
            // this.isDelete = true;
            // this.title = "编辑作业指导书库";
            // this.attachSetting = {
            //   businessId: row.id,
            // };
            // this.show = true;
          },
        },
        column: [
          {
            label: "作业指导书文件名",
            prop: "name",
            sortable: "custom",
          },
          {
            label: "设备分类",
            prop: "typeName",
            sortable: "custom",
          },
          {
            label: "作业类型",
            prop: "group",
            sortable: "custom",
            formatter: (row) => {
              return this.$store.getters.fineDirtDataName(
                "standard_instruction_type",
                row.group
              );
            },
          },
          {
            label: "适用范围",
            prop: "appName",
            sortable: "custom",
          },
          {
            label: "创建人",
            prop: "createByName",
            sortable: "custom",
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
          },
          {
            label: "操作",
            type: "button",
            buttonArr: [
              {
                text: "编辑",
                isShow: () => {
                  return true;
                },
                disabled: !this.$store.getters.isBtnAuth("edit"), //控制按钮的禁用
                content: "未授权功能", //禁用提示内容
                methods: (row, index) => {
                  this.editFormData = row;
                  this.isDelete = true;
                  this.title = "编辑作业指导书库";
                  this.attachSetting = {
                    businessId: row.id,
                  };
                  this.show = true;
                },
              },
            ],
          },
        ],
      },
      formConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "适用范围",
            prop: "appName",
            type: "text",
            span: 12,
            placeholder: "请选择或直接输入",
            disabled: true,
            required: true,
          },
          {
            label: "设备分类",
            prop: "typeName",
            idsStr: "typeId",
            type: "deviceClassify",
            span: 12,
            required: false,
          },
          {
            label: "作业类型",
            prop: "group",
            type: "select",
            span: 12,
            placeholder: "请选择或",
            required: true,
            selectOption: this.$store.getters.dirtData(
              "standard_instruction_type"
            ),
          },
          {
            label: "创建人",
            prop: "createByName",
            type: "text",
            span: 12,
            required: false,
            disabled: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            type: "text",
            span: 12,
            required: false,
            disabled: true,
          },
        ],
      },
      //弹出框表单数据
      editFormData: {},
      attachSetting: {},
      currentData: {},
    };
  },
  mounted() {
    this.$refs.klTable.getTableConfig();
    this.init();
  },
  methods: {
    init() {
      this.$refs.klTable.searchData();
    },
    //获取列表数据
    getTableData(params, sortStr) {
      let queryData = Object.assign({}, params);
      if (sortStr.length > 0) {
        queryData.orders = sortStr;
      }
      queryInstructionList(queryData).then((res) => {
        this.$set(this.tableSetting, "tableData", res.data.records);
        this.$set(this.tableSetting, "totalNumber", res.data.total);
      });
    },
    //上传
    toUpload() {
      this.title = "上传作业指导书";
      this.editFormData = {};
      this.attachSetting = {};
      this.editFormData.appid = this.$store.getters.currentAppInfo.appId;
      this.editFormData.appName = this.$store.getters.currentAppInfo.label;
      this.filesList = [];
      this.show = true;
    },
    //删除作业指导书
    delete() {
      let arr = this.$refs.klTable.getSelectData();
      let ids = [];
      if (arr.length != 0) {
        this.$confirm("确定要删除选中数据吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            arr.forEach((item) => {
              ids.push(item.id);
            });
            deleteInstruction({ ids: ids.join() }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.description);
                this.$refs.klTable.searchData();
              }
            });
            deleteFilesByIds({ businessIds: ids.join() });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("请至少勾选一条数据");
      }
    },
    //提交上传表单
    async doSubmit() {
      try {
        let formData = await this.$refs.editForm.getFormData();
        let uploadFile = this.$refs.attachForm.returnFilsObj();
        let res;
        if (uploadFile.files.length > 0) {
          formData.name = uploadFile.files[0].name;
          let len = uploadFile.files[0].name.split(".").length;
          formData.extension = uploadFile.files[0].name.split(".")[len - 1];
          if (this.title == "上传作业指导书") {
            res = await addInstruction(formData);
            formData.id = res.data;
            this.currentData = formData;
            await this.uploadFile(res.data);
          } else {
            res = await updateInstruction(formData);
            this.currentData = formData;
            await this.uploadFile(formData.id);
          }
          this.$message.success(res.description);
          if (formData.path && uploadFile.files[0].id == formData.path) {
            this.doClose();
            this.$refs.klTable.searchData();
          }
        } else {
          this.$message.warning("上传附件不能为空");
        }
      } catch (error) {}
    },
    //上传文件
    uploadFile(id) {
      new Promise((resolve, reject) => {
        this.attachSetting = { businessId: id };
        resolve(this.attachSetting);
      }).then(() => {
        this.$refs.attachForm.doSubmitFiles();
      });
    },
    async uploadSuccess(data) {
      try {
        let form = this.currentData;
        form.path = data[0].id;
        await updateInstruction(form);
        this.doClose();
        this.$refs.klTable.searchData();
      } catch (error) {}
    },
    //设置为公共标准
    toPublicStandard() {
      let arr = this.$refs.klTable.getSelectData();
      let ids = [];
      if (arr.length != 0) {
        this.$confirm("确定要设为公共标准吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            arr.forEach((item) => {
              ids.push(item.id);
            });
            setCommonInstruction({ ids: ids.join() }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.description);
                this.$refs.klTable.searchData();
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("请至少勾选一条数据");
      }
    },
    //关闭上传表单
    doClose() {
      this.editFormData = {};
      this.filesList = [];
      this.show = false;
    },
    getTableSelectData() {
      return this.$refs.klTable.getSelectData();
    },
  },
};
</script>
<style lang="less" scoped>
.workInstructionLibrary {
  padding: 20px;
  .constentmain {
    //margin-left: 10px;
  }
  .upload-file {
    margin-left: 22px;
    text-align: left;
    display: flex;
    label {
      margin-right: 12px;
    }
    label::before {
      content: "*";
      color: red;
      margin-right: 4px;
    }
  }
}
.flowCloumn {
  display: flex;
  flex-flow: column nowrap;
}
</style>